import axios from 'axios';
import {Message, MessageBox} from 'element-ui';
import store from '../store';
import {getToken} from '../utils/auth';

// 创建axios实例
const service = axios.create({
  // baseURL: process.env.BASE_API, // api的base_url
  timeout: 10000, // 请求超时时间
});
// request拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  let token = getToken()
  if(token){
    config.headers['access-token'] = getToken();
  }
  // if (store.getters.token) {
  //   config.headers['accessToken'] = getToken(); // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  // }
  return config;
}, error => {
  // Do something with request error
  console.log(error); // for debug
  Promise.reject(error);
})

// respone拦截器

service.interceptors.response.use(
  response => {
    const res = response.data;
    console.log( "ciKey<=w>"+JSON.stringify(response.headers['content-disposition']));
    const content = res
    const blob = new Blob([content])
    const fileName = response.headers['filename'];
    const fileName2 = decodeURI(fileName);
    // config.headers['access-token'] = getToken();
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a')
      elink.download = fileName2
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName2)
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
